package com.walter.dynamic.thread.pool.core;

import com.walter.dynamic.thread.pool.ThreadMdcUtil;
import com.walter.dynamic.thread.pool.ThreadPoolMetrics;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.scheduling.concurrent.ExecutorConfigurationSupport;
import org.springframework.util.Assert;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;

/**
 *  动态线程池
 * @author Walter
 * @date 2025/1/24 下午8:30
 **/
@Slf4j
public class DynamicThreadPoolExecutor extends ExecutorConfigurationSupport implements AsyncTaskExecutor {
    // 线程池执行器
    private ThreadPoolExecutor executor;
    private int corePoolSize = 1;
    private int maxPoolSize = Integer.MAX_VALUE;
    private int keepAliveSeconds = 60;
    private int queueCapacity = Integer.MAX_VALUE;
    // 记录总任务数
    private final AtomicLong totalTasks = new AtomicLong(0);
    // 记录已完成任务数
    private final AtomicLong completedTasks = new AtomicLong(0);

    /**
     * 创建线程池
     *
     * @param corePoolSize 核心线程数
     * @param maxPoolSize 最大线程数
     * @param keepAliveSeconds 线程空闲时间,单位秒，超过该时间未被使用的线程将会被回收
     * @param queueCapacity 任务队列
     */
    public DynamicThreadPoolExecutor(int corePoolSize, int maxPoolSize, int keepAliveSeconds, int queueCapacity) {
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        this.keepAliveSeconds =  keepAliveSeconds;
        this.queueCapacity = queueCapacity;
        ThreadFactory threadFactory = getThreadFactory() ;
        this.initializeExecutor(threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());
    }

    /**
     * 动态调整核心线程数
     *
     * @param newCorePoolSize 新的核心线程数
     */
    public void adjustCorePoolSize(int newCorePoolSize) {
        if (newCorePoolSize < 0) {
            throw new IllegalArgumentException("Core pool size cannot be negative");
        }
        int oldCorePoolSize = executor.getCorePoolSize();
        executor.setCorePoolSize(newCorePoolSize);
        log.info("Core pool size adjusted from {} to {}", oldCorePoolSize, newCorePoolSize);
    }


    /**
     * 动态调整最大线程数
     *
     * @param newMaxPoolSize 新最大线程数
     */
    public void adjustMaxPoolSize(int newMaxPoolSize) {
        if (newMaxPoolSize < executor.getCorePoolSize()) {
            throw new IllegalArgumentException("Max pool size cannot be smaller than core pool size");
        }
        int oldMaxPoolSize = executor.getMaximumPoolSize();
        if(newMaxPoolSize == oldMaxPoolSize){
            return;
        }
        executor.setMaximumPoolSize(newMaxPoolSize);
        log.info("Max pool size adjusted from {} to {}", oldMaxPoolSize, newMaxPoolSize);
    }

    /**
     * 获取线程池的性能监控指标
     *
     * @return ThreadPoolMetrics
     */
    public ThreadPoolMetrics getMetrics() {
        return new ThreadPoolMetrics(executor.getActiveCount(),
                executor.getPoolSize(), executor.getMaximumPoolSize(),
                executor.getQueue().size(), totalTasks.get(), completedTasks.get());
    }

    /**
     *  获取线程池
     * @return
     */
    public ThreadPoolExecutor getExecutor() {
        Assert.state(this.executor != null, "ThreadPoolTaskExecutor not initialized");
        return executor;
    }

    @Override
    protected ExecutorService initializeExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedExecutionHandler) {
        BlockingQueue<Runnable> queue = queueCapacity > 0 ? new LinkedBlockingQueue(queueCapacity) : new SynchronousQueue();
        // 创建线程池，使用自定义的线程工厂
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveSeconds,
                TimeUnit.SECONDS, queue,
                threadFactory,
                rejectedExecutionHandler
        );
        super.setWaitForTasksToCompleteOnShutdown(true);
        super.setAwaitTerminationSeconds(60);
        this.executor = executor;
        return executor;
    }

    private ThreadFactory getThreadFactory() {
        return new ThreadFactory() {
            private final AtomicInteger threadNumber = new AtomicInteger(1);
            @Override
            public Thread newThread(Runnable r) {
                Thread t = new Thread(r, "DynamicPool-Thread-" + threadNumber.getAndIncrement());
                // 设置为非守护线程
                t.setDaemon(false);
                return t;
            }
        };
    }
    @Override
    public void execute(Runnable task) {
        totalTasks.incrementAndGet();
        try {
            ExecutorService executor = this.getExecutor();
            executor.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
        } catch (RejectedExecutionException var4) {
            RejectedExecutionException ex = var4;
            throw new TaskRejectedException(executor, task, ex);
        }finally {
            completedTasks.incrementAndGet();
        }
    }
    @Override
    public <T> Future<T> submit(Callable<T> task) {
        totalTasks.incrementAndGet();
        try {
            ExecutorService executor = this.getExecutor();
            return executor.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
        } catch (RejectedExecutionException var4) {
            RejectedExecutionException ex = var4;
            throw new TaskRejectedException(executor, task, ex);
        }finally {
            completedTasks.incrementAndGet();
        }
    }
    @Override
    public Future<?> submit(Runnable task) {
        totalTasks.incrementAndGet();
        try {
            ExecutorService executor = this.getExecutor();
            return executor.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
        } catch (RejectedExecutionException var4) {
            RejectedExecutionException ex = var4;
            throw new TaskRejectedException(executor, task, ex);
        }finally {
            completedTasks.incrementAndGet();
        }
    }
}
